package com.li.streamAPI;

import com.li.java2.Employee;
import com.li.java2.EmployeeData;
import org.junit.Test;

import javax.swing.text.EditorKit;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 喂S别闹
 * @create 2022/4/21-11:43
 * @Version 1.0
 * @Description: 归约与收集
 */
public class StreamAPITest4 {

    @Test
    public void test1() {
//        reduce(T identity,BinaryOperator ) --可以将流中元素反复结合起来
        //计算1-10的和
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 10, 9);
        Integer sum = list.stream().reduce(0, Integer::sum);
        System.out.println(sum);

//        reduce(BinaryOperator) -- 可以将元素反复结合起来，得到值
//        计算公司所有员工工资的总和
        List<Employee> employees = EmployeeData.getEmployees();
        Optional<Double> reduce = employees.stream().map(e -> e.getSalary()).reduce(Double::sum);
        System.out.println(reduce);
    }


    /**
     * @Date: 2022/4/21 11:55
     * @Auther: 喂S别闹
     * @param:
     * @Return: void
     * @Description:收集
     */
    @Test
    public void test2() {
//        collect(Collector c) -- 将流转换为其他形式，接收一个Collector接口的实现
//          练习1：查找工资大于6k的员工，结果返回一个list、set
        List<Employee> employees = EmployeeData.getEmployees();
        List<Employee> collectList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());
        collectList.forEach(System.out::println);

        Set<Employee> collectSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
        collectSet.forEach(System.out::println);

    }
}
